import {
  getQuestionsModel,
  getSingleQuestionModel,
  postQuestionModel,
  updateQuestionModel,
  deleteQuestionModel,
} from "../model/index.js";

// 获取题目列表
export const getQuestions = async (ctx) => {
  try {
    const query = ctx.query;
    const type = query.type || "";
    const keyword = query.keyword || "";
    const pagenum = Math.abs(query.pagenum) || 1;
    const pagesize = Math.abs(query.pagesize) || 10;
    const skip = (pagenum - 1) * pagesize;
    try {
      const result = await getQuestionsModel(type, keyword, skip, pagesize);
      ctx.body = {
        code: 0,
        data: result.data,
        page: {
          total: result.total
        },
        message: "success"
      };
    } catch (err) {
      ctx.body = {
        code: 1,
        data: [],
        page: {
          total: 0
        },
        message: err.message || "获取题目列表失败"
      };
    }
  } catch (err) {
    ctx.body = {
      code: 1,
      data: [],
      page: {
        total: 0
      },
      message: err.message || "获取题目列表失败"
    };
  }
};

// 获取单个题目
export const getSingleQuestion = async (ctx) => {
  try {
    console.log('Received request for question ID:', ctx.params.id);
    const id = parseInt(ctx.params.id);
    
    if (isNaN(id)) {
      console.log('Invalid ID format:', ctx.params.id);
      ctx.status = 400;
      ctx.body = {
        code: 1,
        message: "无效的题目ID",
        data: null
      };
      return;
    }

    console.log('Fetching question with ID:', id);
    const question = await getSingleQuestionModel(id);
    
    if (!question) {
      console.log('Question not found for ID:', id);
      ctx.status = 404;
      ctx.body = {
        code: 1,
        message: "题目未找到",
        data: null
      };
      return;
    }

    console.log('Successfully found question:', question);
    ctx.body = {
      code: 0,
      message: "success",
      data: question
    };
  } catch (err) {
    console.error('Error in getSingleQuestion:', err);
    ctx.status = 500;
    ctx.body = {
      code: 1,
      message: err.message || "获取题目失败",
      data: null
    };
  }
};

// 添加题目
export const postQuestion = async (ctx) => {
  try {
    const body = ctx.request.body;
    const optionsStr = body.options || "";
    let options = [];
    if (optionsStr) {
      options = JSON.parse(optionsStr);
    }
    
    const type = body.type || "";
    const content = body.content || "";
    // const options = body.options || null;
    const answer = body.answer || null;
    let parsedAnswer = null;
    if (type === "多选题" && answer) {
      parsedAnswer = JSON.parse(answer);
    } else {
      parsedAnswer = answer;
    }
    const difficulty = body.difficulty || "medium";
    const language = body.language || null;
    try {
      const result=await postQuestionModel(
        type,
        content,
        options,
        parsedAnswer,
        difficulty,
        language
      );
      ctx.body = {
        code: result.code,
        message: result.message,
        data: result.data,
      };
    } catch (err) {
      ctx.body = {
        code: 1,
        data: null,
        message: err.message || '服务器错误'
      };
      ctx.status = 500;
    }
  } catch (err) {
    throw err;
  }
};

// 更新题目
export const updateQuestion = async (ctx) => {
  try {
    const id = parseInt(ctx.params.id);
    if (isNaN(id)) {
      ctx.status = 400;
      ctx.body = {
        code: 1,
        message: "无效的题目ID",
        data: null
      };
      return;
    }

    const body = ctx.request.body;
    // 先从数据库获取原有的题目数据
    const originalQuestion = await getSingleQuestionModel(id);
    if (!originalQuestion) {
      ctx.status = 404;
      ctx.body = {
        code: 1,
        message: "题目未找到",
        data: null
      };
      return;
    }

    const type = body.type || originalQuestion.type;
    const content = body.content || originalQuestion.content;
    const options = body.options === undefined ? originalQuestion.options : body.options;
    const answer = body.answer === undefined ? originalQuestion.answer : body.answer;
    const difficulty = body.difficulty || originalQuestion.difficulty;
  
    let languageToUpdate = originalQuestion.language; 
    if (body.language !== undefined && typeof body.language === 'string') {
        languageToUpdate = JSON.stringify(body.language.split(','));
    }
    const result = await updateQuestionModel(
      id,
      type,
      content,
      options,
      answer,
      difficulty,
      languageToUpdate
    );

    ctx.body = {
      code: 0,
      message: "更新成功",
      data: result
    };
  } catch (err) {
    console.error('更新题目失败:', err);
    ctx.status = 500;
    ctx.body = {
      code: 1,
      message: err.message || "更新题目失败",
      data: null
    };
  }
};

// 删除题目
export const deleteQuestion = async (ctx) => {
  try {
    let ids = ctx.query.ids; // 支持单个删除和批量删除
    if (typeof ids === 'string') {
        if (ids.startsWith('[')) {
            ids = JSON.parse(ids);
        } else {
            ids = ids.split(',').map(id => parseInt(id));
        }
    }
    if (!Array.isArray(ids)) ids = [parseInt(ids)];
    ctx.body = await deleteQuestionModel(ids);
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: "删除题目时发生错误", details: err.message };
  }
};
